<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item prop="name">
        <el-input v-model="queryParams.name" :placeholder="$t('iot.enterBroadcastName')" clearable size="small" @keyup.enter.native="handleQuery"/>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">{{ $t('common.search') }}</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">{{ $t('common.reset') }}</el-button>
      </el-form-item>
    </el-form>
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="small" @click="handleAdd" v-hasPermi="['iot:radioset:add']">{{ $t('common.add') }}</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="el-icon-edit" size="small" :disabled="single" @click="handleUpdate" v-hasPermi="['iot:radioset:edit']">{{ $t('common.edit') }}</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="el-icon-delete" size="small" :disabled="multiple" @click="handleDelete" v-hasPermi="['iot:radioset:remove']">{{ $t('common.delete') }}</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"/>
    </el-row>
    <el-table v-loading="loading" :data="radiosetList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="45" align="center"/>
      <el-table-column :label="$t('common.id')" align="center" prop="id"/>
      <el-table-column :label="$t('iot.customer')" align="center" prop="nickName" width="155"/>
      <el-table-column :label="$t('iot.project')" align="center" prop="projectname" width="155"/>
      <el-table-column :label="$t('iot.broadcastNo')" align="center" prop="id" />
      <el-table-column :label="$t('iot.broadcastName')" align="center" prop="name" show-overflow-tooltip/>
      <el-table-column :label="$t('iot.playCount')" align="center" prop="playCnt" />
      <el-table-column :label="$t('iot.playVolume')" align="center" prop="playVol" />
      <el-table-column :label="$t('common.remark')" align="center" prop="remark" show-overflow-tooltip/>
      <el-table-column :label="$t('common.createTime')" align="center" prop="createTime" width="156">
        <template slot-scope="scope">{{scope.row.createTime}}</template>
      </el-table-column>
      <el-table-column :label="$t('iot.creator')" align="center" prop="createBy"/>
      <el-table-column :label="$t('common.updateTime')" align="center" prop="updateTime" width="156">
        <template slot-scope="scope">{{scope.row.updateTime||$t('iot.notUpdated')}}</template>
      </el-table-column>
      <el-table-column :label="$t('common.operation')" align="center" class-name="small-padding fixed-width" width="108">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)" v-hasPermi="['iot:radioset:edit']">{{ $t('common.edit') }}</el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)" v-hasPermi="['iot:radioset:remove']">{{ $t('common.delete') }}</el-button>
        </template>
      </el-table-column>
    </el-table>
    <pagination v-show="total>0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize" :page-sizes="pageSizes" @pagination="getList"/>
    <el-dialog :title="title" :visible.sync="open" width="800px" append-to-body>
      <div class="scrollable-content">
        <el-form ref="form" :model="form" :rules="rules" label-width="96px">
          <el-form-item :label="$t('iot.customerName')" prop="customerId">
            <el-select v-model="form.customerId" :placeholder="$t('iot.selectCustomerName')" filterable style="width:100%" @change="handleNicknameChange">
              <el-option v-for="item in options" :key="item.userId" :label="item.nickName" :value="item.userId"/>
            </el-select>
          </el-form-item>
          <el-form-item :label="$t('iot.projectName')" prop="projectId">
            <el-select v-model="form.projectId" :placeholder="$t('iot.selectProjectName')" filterable style="width:100%" @change="handleProjectnameChange">
              <el-option v-for="item in projectnameOptions" :key="item.id" :label="item.projectname" :value="item.id"/>
            </el-select>
          </el-form-item>
          <el-form-item :label="$t('iot.broadcastName')" prop="name">
            <el-input v-model="form.name" :placeholder="$t('iot.enterBroadcastName')" />
          </el-form-item>
          <el-form-item :label="$t('iot.audioFile')" prop="radiofile">
            <audioUpload v-model="form.radiofile" style="width:100%"/>
          </el-form-item>
          <el-form-item :label="$t('iot.playCount')" prop="playCnt">
            <el-input-number v-model="form.playCnt" :placeholder="$t('iot.enterPlayCount')" :min="0"/>
          </el-form-item>
          <el-form-item :label="$t('iot.playVolume')" prop="playVol">
            <el-input-number v-model="form.playVol" :placeholder="$t('iot.enterPlayVolume')" :min="0" :max="100"/>
          </el-form-item>
          <el-form-item :label="$t('common.remark')" prop="remark">
            <el-input v-model="form.remark" type="textarea" :placeholder="$t('common.enterRemark')" />
          </el-form-item>
        </el-form>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">{{ $t('common.confirm') }}</el-button>
        <el-button @click="cancel">{{ $t('common.cancel') }}</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listRadioset, getRadioset, delRadioset, addRadioset, updateRadioset } from "@/api/iot/radioset";
import { listUser } from '@/api/iot/tool'
import { listProject } from '@/api/iot/faproject'
export default {
  name: "Radioset",
  data() {
    return {
      pageSizes: [10,20,30,50],
      options: [],
      projectnameOptions: [],
      loading: true,
      ids: [],
      single: true,
      multiple: true,
      showSearch: true,
      total: 0,
      radiosetList: [],
      title: "",
      open: false,
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        adminId: null,
        customerId: null,
        projectId: null,
        name: null,
        type: null,
        width: null,
        height: null,
        fsize: null,
        json: null,
        refreshtime: null,
        createtime: null,
        updatetime: null,
        deletetime: null,
        weigh: null,
        switch: null,
        state: null,
        lids: null,
        images: null,
        attachfile: null,
        textPTime: null,
        imgPTime: null,
        mp4PTime: null
      },
      form: {},
      rules: {
        customerId: [{ required: true, message: this.$t('iot.customerNameRequired'), trigger: "blur" }],
        projectId: [{ required: true, message: this.$t('iot.projectNameRequired'), trigger: "blur" }],
        name: [{ required: true, message: this.$t('iot.broadcastNameRequired'), trigger: "blur" }],
      }
    };
  },
  created() {
    this.getList();
    this.fetchUsers();
    this.fetchProjectnames();
  },
  methods: {
    async fetchUsers() {
      try {
        const response = await listUser();
        var resList=response.rows;
        if (response && resList) {
          this.options = resList.map(user => ({
            userId: user.userId,
            nickName: user.nickName
          }));
        }
      } catch (error) {
        console.error('error', error);
      }
    },
    async fetchProjectnames() {
      try {
        const response = await listProject();
        var resList=response.rows;
        if (response && resList) {
          this.projectnameOptions = resList.map(item => ({
            id: item.id,  // 用于存储的项目 ID
            projectname: item.projectname,  // 用于展示的项目名称
          }));
          console.log("1:", this.projectnameOptions);
        } else {
          console.error('Invalid response format:', response);
        }
      } catch (error) {
        console.error('Error fetching project names:', error);
      }
    },
    handleNicknameChange(selectedId) {
      const selectedOption = this.options.find(option => option.userId === selectedId);
      if (selectedOption) {
        this.form.customerId = selectedOption.userId;    // 将选择的 userId 存入 adminId 字段
      }
    },
    handleProjectnameChange(selectedId) {
      const selectedOption = this.projectnameOptions.find(option => option.id === selectedId);
      if (selectedOption) {
        this.form.projectId = selectedOption.id;
      } else {
        console.error('No matching data found for value:', value);
      }
    },
    getList() {
      this.loading = true;
      listRadioset(this.queryParams).then(response => {
        this.radiosetList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    cancel() {
      this.open = false;
      this.reset();
    },
    reset() {
      this.form = {
        customerId: null,
        projectId: null,
        id: null,
        adminId: null,
        name: null,
        type: null,
        width: null,
        height: null,
        fsize: null,
        remark: null,
        json: null,
        refreshtime: null,
        createtime: null,
        updatetime: null,
        deletetime: null,
        weigh: null,
        switch: null,
        state: null,
        lids: null,
        images: null,
        attachfile: null,
        textPTime: null,
        imgPTime: null,
        mp4PTime: null
      };
      this.resetForm("form");
    },
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = this.$t('common.add');
    },
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getRadioset(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = this.$t('common.edit');
      });
    },
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateRadioset(this.form).then(response => {
              if(response != undefined){
                this.$modal.msgSuccess(this.$t('common.editSuccess'));
              }
              this.open = false;
              this.getList();
            });
          } else {
            addRadioset(this.form).then(response => {
              if(response != undefined){
                this.$modal.msgSuccess(this.$t('common.addSuccess'));
              }
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm(this.$t('iot.confirmDeleteBroadcast', { ids: ids })).then(function() {
        return delRadioset(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess(this.$t('common.deleteSuccess'));
      }).catch(() => {});
    }
  }
};
</script>
<style>
.scrollable-content {
  max-height: 80vh;   /* 或固定像素值如 600px */
  overflow-y: auto;
  padding-right: 10px; /* 避免滚动条遮挡内容 */
}
</style>
